
import { checkAuthCode, checkToken, getUrlParams } from "./utils/request"
let timer=null
class UnionAuth {
  constructor(options) {
    this.appKey = options.appKey;
    this.token = null;
    this.url = null;
    // console.log("UnionAuth instance created", this.appKey);
    // debugger;
  }
  static authcode;
  static globalVar = "初始化实例";

  ready() {
    // 这里是初始化逻辑，完成后调用
    return new Promise(async (resolve) => {
      this.url = window.location.href;

      // console.log("UnionAuth instance created", this.url);
      // debugger;
      //路径上拿token,先判断是否是hash模式还是history模式
      const urlParams = getUrlParams(this.url);
      console.log(urlParams, "9.3-----urlParams");
      
      this.token = urlParams['dcqc-tk'];
      if(this.token){
        localStorage.setItem('dcqc-tk', this.token);
      }
      UnionAuth.authcode = urlParams['auth_code'];
      let newToken;
      // localStorage取dcqc-tk
      const localStorageToken = localStorage.getItem('dcqc-tk');
      if(localStorageToken && !this.token){
        this.token = localStorageToken
      }
      if (this.token) {
        newToken = await checkToken(this.url, this.token, this.appKey, UnionAuth.authcode);
        // debugger;
        console.log(newToken,'9.18-----newToken');
        
  
      } else {
        newToken = await checkAuthCode(UnionAuth.authcode, this.url, this.appKey)
        // debugger;
        console.log(newToken,'9.18-----newToken2');
      }
      console.log("ready done")
      this.setTimer()
      this.token = newToken;
      resolve(this);

    })
  }
  //设置时间续存1个小时后再次进行调用     1000 * 60 * 60
  setTimer(){
    clearInterval(this.timer)
    this.timer =setInterval(()=>{
        this.ready()
      }, 
      1000*60*60
      )
    };
    

  getToken() {
    if (this.token != null) {
      return this.token;
    } else {
      throw new Error("先初始化ready方法");
    }
  };
  redirectTo(url) {
    if (this.token != null) {
      console.log(`${url}?dcqc-tk=${this.token}`, "9.22222222地址");
      // debugger;
      return window.location.href = `${url}?dcqc-tk=${this.token}`;
    } else {
      throw new Error("先初始化ready方法");
    }
  };
}

export {
  UnionAuth
};